var timestamp = 0;
var enableCache = true;
var updateTime = 600; /* seconds */
var loadingStations = 0;
var clock = null;
var closeInfo = null;
var colors = ['b4b4b4', '2eae00', 'f5e23d', 'f5713d', 'f52424', 'be3df5', '006cb7'];
var coloricons = ['sindatos.png', 'bueno.png', 'regular.png', 'malo.png', 'pesimo.png'];
var zonas = [{"nombre":"Region Lima","zoom":4,"lat":-37.267875,"long":-72.426231},{"nombre":"Regi\u00f3n del Norte","zoom":8,"lat":-18.364561,"long":-69.645723}];
var styles = [
  {
    "featureType": "road.highway.controlled_access",
    "elementType": "geometry",
    "stylers": [
      { "color": "#ffbb4d" }
    ]
  },{
    "featureType": "road.arterial",
    "elementType": "geometry.fill",
    "stylers": [
      { "visibility": "on" },
      { "color": "#ffbb4d " }
    ]
  },{
    "featureType": "administrative.locality",
    "stylers": [
      { "visibility": "on" }
    ]
  },{
  }
];
var styledMap = new google.maps.StyledMapType(styles,{name: "Mapa"});
var map;
var infowindow = new google.maps.InfoWindow;
var markers = [];
function isIE() {
  var myNav = navigator.userAgent.toLowerCase();
  return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
function getUrlVars() {
  var vars = {};
  var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    vars[key] = value;
  });
  return vars;
}
function toggleClass(el, className) {
  if (el.classList) {
    el.classList.toggle(className);
  } else {
      var classes = el.className.split(' ');
      var existingIndex = -1;
      for (var i = classes.length; i--;) {
        if (classes[i] === className)
          existingIndex = i;
      }
  
      if (existingIndex >= 0)
        classes.splice(existingIndex, 1);
      else
        classes.push(className);
  
    el.className = classes.join(' ');
  }
}
function addClass(el, className) {
  if (el.classList) el.classList.add(className);
  else el.className += ' ' + className;
}
function removeClass(el, className) {
  if (el.classList)
    el.classList.remove(className);
  else
    el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
function cambiarVista(el) {
  var center = new google.maps.LatLng(zonas[el.value]['lat'], zonas[el.value]['long']);
  map.setCenter(center);
  map.setZoom(zonas[el.value]['zoom']);
}
function updateStation(marker, key, cache) {
  var selectedPar = document.getElementById('parametro').value;
  var url;
  var markerVisible = false;

  request = new XMLHttpRequest();
  if(cache) {
    //url = 'http://sinca.mma.gob.cl/index.php/json/estacion/key/'+key+'/par/'+selectedPar+'/?time='+timestamp;
    url = '';
  } else {
    //url = 'http://sinca.mma.gob.cl/index.php/json/status/key/'+key+'/par/'+selectedPar+'/?time='+timestamp;
    url = '';
  }
  request.open('GET', url, true);
  
  request.onreadystatechange = function() {
    if (this.readyState === 4){
      if (this.status >= 200 && this.status < 400){
        // Success!
        data = JSON.parse(this.responseText);
        var selectedStatus = document.getElementById('condiciones['+data+']');
        if(data === 0 || !selectedStatus || !selectedStatus.checked) {
          marker.setIcon('img/' + coloricons[0]);
          markerVisible = false;
        } else {
          marker.setIcon('img/' + coloricons[data]);
          markerVisible = true;
        }
        marker.setVisible(markerVisible);
        marker.setZIndex(google.maps.Marker.MAX_ZINDEX + data);
      }
    }
  };
  
  request.send();
  request = null;
  flag=1;
}
function actualizacionEstaciones() {
  var loadingAnimation = document.getElementById('loading');
  if(loadingAnimation) loadingAnimation.style.display = 'block';
  for(var i=0; i<markers.length; i++) {
    updateStation(markers[i][0], markers[i][1], enableCache);
  }
}
function detenerActualizacion() {
  var loadingAnimation = document.getElementById('loading');
  if(loadingAnimation) loadingAnimation.style.display = 'none';
  if(clock) {
    clearInterval(clock);
  }
}
function refrescarEstaciones() {
  detenerActualizacion();
  clock = setInterval(function() {
    actualizacionEstaciones();
  }, updateTime * 1000);
}
function switchUpdate() {
  if(document.getElementById('actualizaEstaciones').checked) {
    refrescarEstaciones();
  } else {
    detenerActualizacion();
  }
}
function drawChart(datos, node, title, ejeX) {
  var data = new google.visualization.DataTable(datos);
  var eje;
  var horas;
  var altura;
  if(ejeX) {
    eje = {
      'textPosition': 'none',
      'baselineColor': '#ccc',
      'gridlines': {
        'color': 'transparent'
      }
    };
    horas = {
      'textPosition': 'out',
      'allowContainerBoundaryTextCufoff': true,
      'baselineColor': 'transparent',
      'gridlines': {
        'color': 'transparent'
      }
    };
    altura = 30;
  } else {
    eje = {
      'textPosition': 'none',
      'baselineColor': 'transparent',
      'gridlines': {
        'color': 'transparent'
      }
    };
    horas = {
      'textPosition': 'none',
      'baselineColor': 'transparent',
      'gridlines': {
        'color': 'transparent'
      }
    };
    altura = 30;
  }

  var options = {
    'width': 245,
    'height': altura,
    'title': title,
    'titlePosition': 'in',
    'tooltip': {
      'trigger': 'focus',
      'isHtml': true
    },
    'legend': {
      'position': 'none'
    },
    'chartArea': {'width': '100%', 'height': '100%'},
    'hAxis': horas,
    'vAxis': eje,
    'charArea': {
      'top': 0,
      'right': 0,
      'bottom': 0,
      'left': 0
    }
  };

  var chart = new google.visualization.ColumnChart(node);
  chart.draw(data, options);
}
function cargaInfo(node, stnId, parId, ejeX) {
  /* consulta por estaciones en línea y mantiene los marcadores ocultos */
  var request = new XMLHttpRequest();
  var reponseText;
  var returnValue = null;
  request.open('GET', 'http://sinca.mma.gob.cl/cgi-bin/datatable.cgi?domain=CONAMA&stn='+stnId+'&par='+parId+'&time='+timestamp, true);
  request.onreadystatechange = function() {
    if (this.readyState === 4) {
      if (this.status >= 200 && this.status < 400) {
        switch(parId) {
          case 'PM10':
            title = 'MP 10';
            break;
          case 'PM25':
            title = 'MP 2.5';
            break;
          case '0001':
            title = 'Dióxido de azufre';
            break;
          case '0003':
            title = 'Dióxido de nitrógeno';
            break;
          case '0004':
            title = 'Monóxido de carbono';
            break;
          case '0008':
            title = 'Ozono';
            break;
        }
        var datos = JSON.parse(this.responseText);
        if(datos.status > 0) {
          drawChart(datos.info, node, title, ejeX);
        }
      }
    }
  }
  request.send();
  request = null;
}
function hasClass(el, className) {
  if(el.classList) {
    return el.classList.contains(className);
  } else {
    var check = new RegExp('(^| )' + className + '( |$)', 'gi');
    return check.test(el.className);
  }
}
function showNiveles() {
  var tab1 = document.getElementById('tab1');
  var tab2 = document.getElementById('tab2');
  removeClass(tab1, 'hidden');
  addClass(tab2, 'hidden');
}
function showHorarios() {
  var tab1 = document.getElementById('tab1');
  var tab2 = document.getElementById('tab2');
  removeClass(tab2, 'hidden');
  addClass(tab1, 'hidden');
}
function attachInfoBox(marker, stnId, stnName, stnComuna, stnRed, urlRed) {
  
  google.maps.event.addListener(marker, 'click', function() {
    var nodePM10 = document.createElement('div');
    cargaInfo(nodePM10, stnId, 'PM10', true);

    var nodePM25 = document.createElement('div');
    cargaInfo(nodePM25, stnId, 'PM25', true);

    var node0001 = document.createElement('div');
    cargaInfo(node0001, stnId, '0001', true);

    var node0003 = document.createElement('div');
    cargaInfo(node0003, stnId, '0003', true);

    var node0004 = document.createElement('div');
    cargaInfo(node0004, stnId, '0004', true);

    var node0008 = document.createElement('div');
    cargaInfo(node0008, stnId, '0008', true);

    var parentNode = document.createElement('div');
    addClass(parentNode, 'popupInfo');

    var titleNode = document.createElement('h1');
    titleNode.appendChild(document.createTextNode(stnName));

    var a = document.createElement('a');
    var linkText = document.createTextNode("ver ficha");
    a.appendChild(linkText);
    a.title = "Ir a ficha de estación";
    a.href = "http://sinca.mma.gob.cl/index.php/estacion/index/key/"+stnId;
    a.target = "_blank";
    addClass(a, 'ficha');

    var comunaNode = document.createElement('p');
    addClass(comunaNode, 'comuna');
    comunaNode.appendChild(document.createTextNode(stnComuna));

    var titleQueryTime = document.createElement('p');
    addClass(titleQueryTime, 'timestamp');

    request = new XMLHttpRequest();
    request.open('GET', 'http://sinca.mma.gob.cl/cgi-bin/datetime.cgi', true);
    request.onreadystatechange = function() {
      if (this.readyState === 4) {
        if (this.status >= 200 && this.status < 400) {
          titleQueryTime.appendChild(document.createTextNode(JSON.parse(this.responseText).datetime));
          timestamp = JSON.parse(this.responseText).timestamp;
        }
      }
    }
    request.send();
    request = null;

    var tabla = document.createElement('div');

    request = new XMLHttpRequest();
    request.open('GET', 'http://sinca.mma.gob.cl/cgi-bin/stnresume.cgi?domain=CONAMA&stn='+stnId+'&time='+timestamp, true);
    request.onreadystatechange = function() {
      if (this.readyState === 4) {
        if (this.status >= 200 && this.status < 400) {
          tabla.innerHTML = this.responseText;
        }
      }
    }
    request.send();
    request = null;
    
    var tablahorarios = document.createElement('div');

    request = new XMLHttpRequest();
    request.open('GET', "http://sinca.mma.gob.cl/cgi-bin/registrostable.cgi?domain=CONAMA&stn="+stnId+"&output="+stnName, true);
    request.onreadystatechange = function() {
      if (this.readyState === 4) {
        if (this.status >= 200 && this.status < 400) {
          tablahorarios.innerHTML = this.responseText;
        }
      }
    }
    request.send();
    request = null;
    
    var b = document.createElement('a');
    var linkDescargaB = document.createTextNode("niveles");
    b.appendChild(linkDescargaB);
    b.href = "javascript:showNiveles();";
    addClass(b, 'graficos');
    
    var c = document.createElement('a');
    var linkDescargaC = document.createTextNode("concentraciones horarias");
    c.appendChild(linkDescargaC);
    c.href = "javascript:showHorarios();";
    addClass(c, 'descarga');
    
    var d = document.createElement('a');
    var linkDescargaD = document.createTextNode("descargar CSV");
    d.appendChild(linkDescargaD);
    d.href = 'http://sinca.mma.gob.cl/cgi-bin/registros.cgi?domain=CONAMA&stn='+stnId+'&output='+stnName;
    addClass(d, 'download');

    var cleanDiv = document.createElement('div');
    addClass(cleanDiv, 'break');
    var cleanDiv2 = cleanDiv.cloneNode(true);
    
    var halfWidth = document.createElement('div');
    addClass(halfWidth, 'half');
    var halfWidth2 = halfWidth.cloneNode();
    addClass(halfWidth2, 'step');

    var tab1 = document.createElement('div');
    var tab2 = document.createElement('div');
    tab1.setAttribute('id','tab1');
    tab2.setAttribute('id','tab2');
    addClass(tab2, 'hidden');

    parentNode.appendChild(titleNode);
    parentNode.appendChild(comunaNode);
    parentNode.appendChild(a);
    parentNode.appendChild(b);
    parentNode.appendChild(c);
    parentNode.appendChild(d);
    parentNode.appendChild(cleanDiv);
    halfWidth.appendChild(nodePM25);
    halfWidth.appendChild(nodePM10);
    halfWidth.appendChild(node0001);
    halfWidth.appendChild(node0003);
    halfWidth.appendChild(node0004);
    halfWidth.appendChild(node0008);
    halfWidth.appendChild(titleQueryTime);
    halfWidth2.appendChild(tabla);
    tab1.appendChild(halfWidth);
    tab1.appendChild(halfWidth2);
    tab2.appendChild(tablahorarios);
    parentNode.appendChild(tab1);
    parentNode.appendChild(tab2);
    parentNode.appendChild(cleanDiv2);

    map.panTo(marker.getPosition());

    infowindow.close();
    infowindow.setContent(parentNode);
    infowindow.open(map, marker);
    updateStation(marker, stnId, false);
    removeClass(document.getElementById('controlesMapaId'), 'active');

    clearInterval(closeInfo);
    closeInfo = setTimeout(function() {
      infowindow.close();
    }, updateTime * 1000);
  });
}

/* Función de inicio de carga para el mapa Google */
function initialize() {
  /* configuración de elemento mapa Google */
  var mapOptions = {
    zoom: 4,
    mapTypeId: google.maps.MapTypeId.HYBRID,
    scaleControl: true,
    streetViewControl: false,
    scrollwheel: false,
    center: new google.maps.LatLng(-37.267875, -72.426231),
    panControl: true,
    panControlOptions: {
      position: google.maps.ControlPosition.TOP_RIGHT
    },
    zoomControl: true,
    zoomControlOptions: {
      style: google.maps.ZoomControlStyle.LARGE,
      position: google.maps.ControlPosition.TOP_RIGHT
    },
    scaleControl: true,
    streetViewControl: false
  };

  /* creación de elemento mapa Google */
  map = new google.maps.Map(document.getElementById('mapaNacional'), mapOptions);
  map.mapTypes.set('map_style', styledMap);
  map.setMapTypeId('map_style');

  /* permite ocultar panel lateral al evento click sobre el mapa, no sobre los marcadores */
  google.maps.event.addListener(map, 'click', function() {
    removeClass(controlesMapaId, 'active');
  });

  /* selecciona zona por defecto según valores de variable "z" (tipo GET) acorde a los valores presentes en elemento SELECT con id "region" */
  var zonaSeleccionada = getUrlVars()["z"];
  var regionSelect = document.getElementById('region');
  if(zonaSeleccionada) regionSelect.value = zonaSeleccionada;
  else regionSelect.value = 0;
  cambiarVista(regionSelect);

  request = new XMLHttpRequest();
  request.open('GET', 'http://sinca.mma.gob.cl/cgi-bin/datetime.cgi', true);
  request.onreadystatechange = function() {
    if (this.readyState === 4) {
      if (this.status >= 200 && this.status < 400) {
        timestamp = JSON.parse(this.responseText).timestamp;
      }
    }
  }
  request.send();
  request = null;

  /* consulta por estaciones en línea y mantiene los marcadores ocultos */
  request = new XMLHttpRequest();
  request.open('GET', 'http://sinca.mma.gob.cl/index.php/json/listado/?time='+timestamp, true);
  request.onreadystatechange = function() {
    if (this.readyState === 4) {
      if (this.status >= 200 && this.status < 400) {
        data = JSON.parse(this.responseText);
        for(var i=0; i<data.length; i++) {
          var place = new google.maps.LatLng(data[i]['latitud'], data[i]['longitud']);
          var marker = new google.maps.Marker({
            position: place,
            map: map,
            title: data[i]['nombre'],
            icon: {
              url: 'img/sindatos.png'
            },
            visible: false
          });
          attachInfoBox(marker, data[i]['key'], data[i]['nombre'], data[i]['comuna'], data[i]['red'], data[i]['urlRed']);
          markers.push([marker, data[i]['key']]);
        }
      }
    }
  }
  request.send();
  request = null;

  toggleClass(document.getElementById('controlesMapaId'), 'active');
    
  var comunaNode = document.getElementById('secondsToUpdate');
  comunaNode.appendChild(document.createTextNode(' cada '+ updateTime +' segundos'));

  /* actualización periódica de estaciones */
  clock = setInterval(function() {
    actualizacionEstaciones();
  }, updateTime * 1000);

  setTimeout(function() {
    actualizacionEstaciones();
    enableCache = false;
  }, 1000);
  map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('legend'));
}
google.load("visualization", "1", {packages:["corechart"]});
google.maps.event.addDomListener(window, 'load', initialize);